<template>
<div class="thisPage" id="top">
  
  <div><h1 style="text-align: center;">试题组卷</h1></div>
  <div class="content_row">
    <div class="questionTable"> 

      <el-table :data="state.questionList" style="width: 100%" border 
          
      :row-style="{height:50+'px'}" 
      :cell-style="{padding:0+'px'}" 
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      >    
        <el-table-column type="index" width="45" label="序" />
        <el-table-column width="500" property="content" label="内容" show-overflow-tooltip />
        <el-table-column width="70" property="type_cn" label="题型" /> 
        <el-table-column align="right" width="55" >
          <template #header>
            <p>操作</p>
          </template>
          <template #default="scope"> 
            <el-tooltip
              class="box-item"
              effect="dark"
              content="上调"
              placement="top"
            >
              <el-icon style="width: 1em; height: 1em; margin-right: 1px" @click="swapUp(scope.$index)">
                <Top />
              </el-icon>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="下调"
              placement="top"
            >
              <el-icon style="width: 1em; height: 1em; margin-right: 1px" @click="swapDown(scope.$index)">
                <Bottom />
              </el-icon>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>  
    <div class="paperForm">
      <el-form
        ref="paperFormRef"
        :model="paperForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm" 
        status-icon
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="paperForm.title" clearable/>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" :icon="View" @click="VerifyPaperTitle()">检测试卷标题</el-button>
        </el-form-item>      
        <el-form-item label="备注" prop="description">
          <el-input v-model="paperForm.description" type="textarea" />
        </el-form-item>    -->
        
        <el-form-item>
          <el-button type="primary" @click="viewAllInformation()">预览</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>        
        </el-form-item>
      </el-form>
      <p>总费用为：<el-text class="mx-1" type="danger" size="large">{{ state.paymentAmount }}</el-text></p>
      
    </div>
  </div>
</div>
    <ShowQuestionReadOnlyDialog ref="showQuestionReadOnlyDialog" :questionList="state.questionList"></ShowQuestionReadOnlyDialog>
</template>
  
<script setup>
  import axios from '@/utils/axios'
  import { useStore } from 'vuex'
  import { reactive, ref, onMounted, getCurrentInstance } from 'vue'
  import { View  } from '@element-plus/icons-vue'
  import { UploadFilled, Top, Bottom } from '@element-plus/icons-vue'
  import { localGet, uploadPaperFileServer} from '@/utils'
  import { ElMessage } from 'element-plus'
  import { useRouter, } from 'vue-router'
  import ShowQuestionReadOnlyDialog from '@/views/ShowQuestionReadOnlyDialog.vue'
 
  const localUser = localGet('user_information')
  const showQuestionReadOnlyDialog = ref()
  const router = useRouter()
  const persistencePaper = ref(false)
  const paperFormRef = ref(null)
  const multipleTableRef = ref(null)
  const store=useStore()
  // let questionList = reactive(null)    //用于发送给服务器后端
  const paperForm = reactive({
    title: '试卷标题',
    description: '写下备注哦',
    is_joint: false,
    open_level: 'private',
    publish:'',
  })
  const state = reactive({
    QueryPaymentAmount:0,
    questionList: [],
  })
  const rules = reactive({
    title: [
      { required: true, message: '请输入试卷标题', trigger: 'blur' },
      { min: 4, max: 50, message: '长度的合适范围是4-50字', trigger: 'blur' },
    ],
    description: [
      {
        required: false,
        message: '请输入备注',
        trigger: 'change',
      },
    ], 
  })
  onMounted(()=>{
    //对数组进行深拷贝
    state.questionList = [].concat(JSON.parse(JSON.stringify(store.state.selectQuestionList)))
    // console.log('从vuex中传过来的数据：', state.questionList)
    scrollToTop()
    QueryPaymentAmount()
  })
  //把题目中的<br>转换成\n
  var re1 = /<br>/g
  var re2 = /<p>/g
  var re3 = /<\/p>/g
  var re4 = /&nbsp;/g
  var re5 =/&gt;/g
  var re6 = /&lt;/g
  var re7 = /&quot;/g
  const convertbr2enter = (strbr)=>{
    if(strbr==""){
      return strbr
    }
    strbr = strbr.replace(re1, "\n")
    strbr = strbr.replace(re2, "")
    strbr = strbr.replace(re3, "\n")
    strbr = strbr.replace(re4, " ")
    strbr = strbr.replace(re5, ">")
    strbr = strbr.replace(re6, "<")
    strbr = strbr.replace(re6, "")
    strbr = strbr.replace(re7, "\"")
    return strbr
   }
   //把题目中题干中的插入和解析中的插图去掉http://ip部分
   const discard_prefix=(array)=>{
    var re = /\/static\/images\/(\w+)\.((jpg)|(jpeg)|(png))/g
    var pictures = ""     
    if(array.length==0){
      pictures = ""
    }else if(array.length==1){
      pictures= array[0].match(re)
      pictures=pictures.toString()
    }else{
      let temp_images = []
      for(let item of array){
        let picture= item.match(re)
        temp_images.push(picture)
      }
      pictures=temp_images.join("-")
    }
    return pictures
   }
   //把题目列表中的题目内容、答案、解析文字、题干插图、解析插入进行转换
  const convertQuestionListbr2Enter = (array)=>{
    for(let i=0;i<array.length;i++){
      array[i].content = convertbr2enter(array[i].content_front)
      array[i].answer = convertbr2enter(array[i].answer_front)
      array[i].explain = convertbr2enter(array[i].explain_front)
      // array[i].pictures = discard_prefix(array[i].images)
      // array[i].pictures_explain = discard_prefix(array[i].images_explain)
    }
    return array
  }
  // 回到顶部
  const scrollToTop=()=>{
    document.querySelector('#top').scrollIntoView(true);
  }
  //把题目中的<br>转换成\n，在提交给后台，返回文件的url
  const submitForm =  () => {    
    paperFormRef.value.validate((vaild, obj) => {
      if (vaild) {
        if(VerifyPaperTitle()==false){
          ElMessage.error("请修改相关地方！")
          return false
        }
        if(state.paymentAmount > localUser.bank_point) {
          ElMessage.error("余额不足，请联系管理员充值后再下载！")
          return false
        }
        console.log("转换格式之前：",state.questionList)
        // state.questionList=convertQuestionListbr2Enter(state.questionList)
        console.log("提交题目列表：", state.questionList)
        let question_list_form = []
        for(let item of state.questionList){
          question_list_form.push({
            content: item.content,
            answer: item.answer,
            explain: item.explain,
            // pictures: item.pictures,
            // pictures_explain: item.pictures_explain,
            type: item.type,
            knowledgepoint:item.knowledgepoint,
            open_level: item.open_level,
            owner: item.owner_info,
            bank_point: item.bank_point
          })
        }
        let params = {        
            questionList: question_list_form,
            paperInformation: paperForm
        }
        console.log("组卷发给后端前：", params.questionList)   
        axios.post('/QuestionList2DocxFile/', params, {responseType: "blob"}).then((response) => {        
          console.log("文件下载：",response)
          const url = window.URL.createObjectURL(new Blob([response]));
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', 'download.docx');
          // link.style.display = 'none';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link)
          router.go(-1)
        }).catch((error)=>{
        console.log("发送已选题目错误：", error)
        })
      }else{                //输出表单没有通过的原因
        console.log("表单没有通过！",obj)
        for (let key in obj) {
          console.log(obj[key][0].message)
          return false;
        }
      }
    })
  }
  // 查询下载所需的库币
  const QueryPaymentAmount=()=>{
    let questionIdList = new Array()
    if(state.questionList.length==0){
      ElMessage.error('请先选择题目！')
      return false
    }
    console.log("组卷题目列表:",state.questionList)
    for(let item of state.questionList){
      questionIdList.push(item.id)
    }
    questionIdList = questionIdList + ''
    console.log('题目id列表:', questionIdList)
    axios.get('/PaymentAmountWithDownloadQuestionApiView/',{params:{questionList:questionIdList}}).then(res => {
      if (res.code==200){
        state.paymentAmount = res.data.results
      }else{
        ElMessage.warning('sorry，查询下载所需的库币错误') 
      }
    })
    .catch((error)=>{
      console.log("下载库币查询失败", error)
      return false
    })  
  }
  //检测试卷名称是否重名
  const VerifyPaperTitle=()=>{
      axios.get('/VerifyPaperName/',{params:{paper_title:paperForm.title}}).then(res => {
      if (res.code==200){
        ElMessage.success('恭喜，该标题可以使用^_^')
        return true
      }else{
        ElMessage.warning('sorry，该标题已被使用*_*,请更换新标题')
        return false
      }        
    })
    .catch((error)=>{
      console.log("监测试卷重名error", error)
      return false
    })   
  }

  //查看题目列表
  const viewAllInformation=()=>{   
    showQuestionReadOnlyDialog.value.open(state.questionList)
  }
  // 判断当前用户是否为管理员
  const isStaff=()=>{
    let localUser = localGet('user_information')
    return localUser.is_staff == true
  }
  // 当前行上调
  const swapUp=(index)=>{
    if(index == 0){
      return false
    }
    let t
    t=state.questionList[index]
    state.questionList[index]=state.questionList[index-1]
    state.questionList[index-1]=t
  }
  // 当前行下调
  const swapDown=(index)=>{
    if(index == state.questionList.length-1){
      return false
    }
    let t
    t=state.questionList[index]
    state.questionList[index]=state.questionList[index+1]
    state.questionList[index+1]=t
}
</script>

<style scoped>
  .thisPage{
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    align-items: center;
  }
  .content_row{
    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    align-items: flex-start;
  }
  .questionTable{
    padding: 0;
    margin: 0 20px 0 0;
  }
  .paperForm{
    width: 300px;
    border-style: solid;
    border-color: rgb(83, 79, 79);
    border-width: 1px;
  }
</style>